import os
import time

from application import SETTINGS
from elu.base.handler import BaseHandler
from elu.base.helper import sizeof_fmt

warehouse = os.path.join(SETTINGS['static_path'], "_upload")


class SandboxHandler(BaseHandler):
    def get(self):
        node_list = []
        if os.path.exists(warehouse):
            for i in os.listdir(warehouse):
                a = os.stat(os.path.join(warehouse, i))
                # Add 28800 seconds, transfer UTC to localtime
                structed_time = time.strptime(time.ctime(a.st_ctime+28800), "%a %b %d %H:%M:%S %Y")
                node_list.append([
                    i,
                    time.strftime("%Y/%m/%d %H:%M", structed_time),
                    sizeof_fmt(a.st_size)
                ])
        self.render("sandbox/show.html", node_list=node_list)


class SandboxUploadHandler(BaseHandler):
    def post(self):
        parcel = self.request.files['fill'][0]
        if not os.path.exists(warehouse):
            os.makedirs(warehouse)
        destination = os.path.join(warehouse, parcel.filename)
        writeFileData = open(destination, "wb")
        writeFileData.write(parcel.body)


class SandboxDownloadHanlder(BaseHandler):
    def get(self, item):
        parcel_path = os.path.join(warehouse, item)
        if not item or not os.path.exists(parcel_path):
            raise HTTPError(404)

        self.set_header('Content-Type', 'application/force-download')
        self.set_header('Content-Disposition', 'attachment; filename=%s' % item)
        with open(parcel_path, "rb") as f:
            try:
                while True:
                    _buffer = f.read(4096)
                    if _buffer:
                        self.write(_buffer)
                    else:
                        f.close()
                        self.finish()
                        return
            except:
                raise HTTPError(404)
        raise HTTPError(500)

